/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.fzhucc.modules.elegant.service;

import com.fzhucc.modules.Msg.domain.Msg;
import com.fzhucc.modules.Msg.domain.dto.SmallMsgDto;
import com.fzhucc.modules.Msg.repository.MsgRepository;
import com.fzhucc.modules.elegant.domain.Elegant;
import com.fzhucc.modules.elegant.domain.dto.ElegantAddEditDto;
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService;
import com.fzhucc.modules.notice.domain.dto.NoticeDto;
import com.fzhucc.modules.notice.domain.dto.NoticeQueryCriteria;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.domain.UserSmall;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.repository.UserSmallRepository;
import com.fzhucc.modules.system.service.dto.UserDto;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.elegant.repository.ElegantRepository;
import com.fzhucc.modules.elegant.domain.dto.ElegantDto;
import com.fzhucc.modules.elegant.domain.dto.ElegantQueryCriteria;
import com.fzhucc.modules.elegant.service.mapstruct.ElegantMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author yyg
* @date 2024-01-23
**/
@Service
@RequiredArgsConstructor
public class ElegantService {

    private final ElegantRepository elegantRepository;
    private final ElegantMapper elegantMapper;

    private final UserRepository userRepository;

    private final FenRecordLogService fenRecordLogService;

    private final MsgRepository msgRepository;

    private final UserSmallRepository userSmallRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${fen.type.fc}")
    public String fc;


    //根据不同设置不同的部门查看
    public String setCriteria(ElegantQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    public Map<String,Object> queryAll(ElegantQueryCriteria criteria, Pageable pageable){
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(fc);
        } catch (Exception e) {

        }

        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
                if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                    //TODO 即查询参数有参数  省总账号查具体模糊查询
                    String[] orgAreas = criteria.getOrgAreas();
                    criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
                }
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                //传参要查的 orgArea
                String csOrgArea = orgAreas[orgAreas.length - 1];
                //登录用户的 orgArea
                String dlOrgArea = criteria.getOrgArea();
                if (dlOrgArea == null) { //表示省总
                    criteria.setOrgArea(csOrgArea);
                } else {
                    //不是省总  登录的 存在  传进来的全部 则可以 否则则使用登录的
                    String[] split = dlOrgArea.split(";");
                    if (split.length == 1) {
                        //表示为省
                        if (split[0].equals(all)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            //其他省 则 传进来的第一个和这个省一致才返回数据
                            String orgArea = orgAreas[0];
                            if (split[0].equals(orgArea)) {
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 2) {
                        //例 ： 福建省;福州市;
                        String s = split[1];
                        if (orgAreas.length == 3) {
                            //福建省;福州市;马尾区;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                        if (orgAreas.length == 2) {
                            //福建省;福州市;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 3) {
                        //例 ： 福建省;福州市;马尾区;  相符就查马尾区  不相符就查登录用户的区域
                        String s = split[2];
                        if (s.equals(csOrgArea)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            criteria.setOrgArea(dlOrgArea);
                        }
                    }
                }
            }
        }

        criteria.setIsDelete(0);
        Page<Elegant> page = elegantRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);

        Page<ElegantDto> map = page.map(elegantMapper::toDto);
        List<ElegantDto> list = map.getContent();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                ElegantDto dto = list.get(i);
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<ElegantDto> queryAll(ElegantQueryCriteria criteria){
        criteria.setIsDelete(0);
        return elegantMapper.toDto(elegantRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Transactional
    public ElegantDto findById(Integer id) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(fc);
        } catch (Exception e) {

        }

        Elegant elegant = elegantRepository.findById(id).orElseGet(Elegant::new);
        ValidationUtil.isNull(elegant.getId(),"Elegant","id",id);
        ElegantDto elegantDto = elegantMapper.toDto(elegant);

        String orgArea = elegantDto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            elegantDto.setOrgAreas(array);
        } else {
            String[] array = {};
            elegantDto.setOrgAreas(array);
        }

        List<Msg> listMsg = msgRepository.findNormalByGlIdWithAuditStatus(elegantDto.getId(), "审核通过","%风采%");
        if (listMsg != null && listMsg.size() > 0) {
            List<SmallMsgDto> myList = new ArrayList<SmallMsgDto>();
            for (Msg msg : listMsg) {
                SmallMsgDto smallMsgDto = new SmallMsgDto();
                smallMsgDto.setId(msg.getId());
                smallMsgDto.setGlId(msg.getGlId());
                smallMsgDto.setType(msg.getType());
                smallMsgDto.setContext(msg.getContext());
                smallMsgDto.setAuditStatus(msg.getAuditStatus());
                smallMsgDto.setUserId(msg.getUserId());
                smallMsgDto.setUpdateBy(msg.getUpdateBy());
                smallMsgDto.setCreateTime(msg.getCreateTime());
                smallMsgDto.setCreateBy(msg.getCreateBy());
                smallMsgDto.setUpdateTime(msg.getUpdateTime());
                Optional<UserSmall> res = userSmallRepository.findById(msg.getUserId());
                if (res.isPresent()) {
                    smallMsgDto.setUserSmall(res.get());
                }
                myList.add(smallMsgDto);
            }
            elegantDto.setMsgDto(myList);
        }
        return elegantDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public ElegantDto create(ElegantAddEditDto dto) {
        Elegant resources = new Elegant();
        resources.setContext(dto.getContext());
        resources.setIsDelete(0);
        resources.setSort(dto.getSort());
        resources.setTitle(dto.getTitle());
        resources.setPic(dto.getPic());
        resources.setIsShow(dto.getIsShow());
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        return elegantMapper.toDto(elegantRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(ElegantAddEditDto dto) {
        Elegant elegant = elegantRepository.findById(dto.getId()).orElseGet(Elegant::new);
        ValidationUtil.isNull( elegant.getId(),"Elegant","id",dto.getId());
        elegant.setIsShow(dto.getIsShow());
        elegant.setSort(dto.getSort());
        elegant.setTitle(dto.getTitle());
        elegant.setPic(dto.getPic());
        elegant.setContext(dto.getContext());
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            elegant.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            elegant.setOrgArea(orgAreaReturn());
        }
        elegantRepository.save(elegant);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            //elegantRepository.deleteById(id);
            Optional<Elegant> res = elegantRepository.findById(id);
            if (res.isPresent()) {
                Elegant elegant = res.get();
                elegant.setIsDelete(1);
                elegantRepository.save(elegant);
            }
        }
    }

    public void download(List<ElegantDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ElegantDto elegant : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("富文本内容", elegant.getContext());
            map.put("h5是否展示 默认否", elegant.getIsShow());
            map.put("排序", elegant.getSort());
            map.put("标题", elegant.getTitle());
            map.put("图片", elegant.getPic());
            map.put("是否删除 默认否", elegant.getIsDelete());
            String orgArea = elegant.getOrgArea();
            if (orgArea != null) {
                if (orgArea.contains(";")) {
                    String[] split = orgArea.split(";");
                    String str = "";
                    for (String a : split) {
                        str = str + a + "/";
                    }
                    map.put("所属工会", str);
                } else {
                    map.put("所属工会", orgArea);
                }
            } else {
                map.put("所属工会", "");
            }
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}